package com.ruoyi.manage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DESUtil;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.WXCore;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.manage.config.AppConfig;
import com.ruoyi.manage.config.WxApiConfig;
import com.ruoyi.manage.domain.AppUser;
import com.ruoyi.manage.domain.request.EncryptedRequest;
import com.ruoyi.manage.domain.request.LoginRequest;
import com.ruoyi.manage.mapper.AppUserMapper;
import com.ruoyi.manage.service.AppLoginService;
import com.ruoyi.manage.service.IAppUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wwy
 * @Date: 2020/12/29 15:09
 */
@Service
public class AppLoginServiceImpl implements AppLoginService {
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private AppUserMapper appUserMapper;
    /**
     * 数据加密密钥
     */
    @Value("${dataPassword}")
    private String dataPassword;
    /**
     * 1.获取code,调用微信登录接口，获取openid
     * 2.保存进入数据库
     * 3.生成token并保存
     * @param code
     * @return
     */
    @Override
    public AjaxResult login(String code) {
        if(StringUtils.isEmpty(code)){
            throw new CustomException("code为空", HttpStatus.BAD_REQUEST);
        }
        String appId = DictUtils.getDictValue("wx_config", "app_id", "");
        String appSecret = DictUtils.getDictValue("wx_config", "app_secret", "");
        String url = WxApiConfig.LOGIN;
        String param = "appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
        String responseLogin = HttpUtils.sendGet(url, param);
        if(StringUtils.isEmpty(responseLogin)){
            throw new CustomException("系统内部错误",HttpStatus.ERROR);
        }
        Map<String,Object> map = JSONObject.parseObject(responseLogin, Map.class);
        Object openidObj = map.get("openid");
        if(openidObj == null){
            throw new CustomException("系统内部错误",HttpStatus.ERROR);
        }
        String session_key = String.valueOf(map.get("session_key"));
        String openId = String.valueOf(openidObj);
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);
        List<AppUser> appUsersList = iAppUserService.selectAppUserList(appUser);
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("openId",openId);
        returnMap.put("session_key",session_key);
        if(appUsersList.size()<=0) {
            //抛出用户未实名认证
            return new AjaxResult(HttpStatus.REAL_NAME_AUTHENTICATION, "用户未实名认证", returnMap);
        }
        if(appUsersList.size()>1){
            throw new CustomException("系统内部错误",HttpStatus.ERROR);
        }

        if(appUsersList.size()==1){
            AppUser appUser1 = appUsersList.get(0);
            //获取绑定状态：
            if(appUser1.getBindingStatus() == 0){
                //未绑定
                return new AjaxResult(HttpStatus.REAL_NAME_AUTHENTICATION, "用户未实名认证", returnMap);
            }

            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            //修改登录ip
            appUser1.setLastLoginIp(ip);
            iAppUserService.updateAppUser(appUser1);
        }

        return AjaxResult.success(returnMap);
    }

    /**
     * 获取手机号
     * @param encryptedRequest
     * @return
     */
    @Override
    public AjaxResult getPhone(EncryptedRequest encryptedRequest) {
        if(encryptedRequest == null || StringUtils.isEmpty(encryptedRequest.getEncryptedData()) || StringUtils.isEmpty(encryptedRequest.getIv()) || StringUtils.isEmpty(encryptedRequest.getSessionKey())){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        String appId = DictUtils.getDictValue("wx_config", "app_id", "");
        String decrypt = WXCore.decrypt(appId, encryptedRequest.getEncryptedData(), encryptedRequest.getSessionKey(), encryptedRequest.getIv());
        Map map1 = JSONObject.parseObject(decrypt, Map.class);
        return AjaxResult.success(map1);
    }

    /**
     * 解除绑定
     * 修改用户状态为解除绑定
     * @param openId
     * @return
     */
    @Override
    public AjaxResult removeBinding(String openId) {
        //根据openId查询
        AppUser appUser1 = new AppUser();
        appUser1.setOpenId(openId);
        List<AppUser> appUsers = iAppUserService.selectAppUserList(appUser1);
        if(appUsers.size()<1){
            throw new CustomException("解除绑定失败", HttpStatus.ERROR);
        }
        AppUser appUser = new AppUser();
        appUser.setId(appUsers.get(0).getId());
        appUser.setBindingStatus(0);
        appUser.setIdentitynumber("");
        appUser.setPhone("");
        appUser.setAddress("");
        appUser.setBirth("");
        appUser.setName("");
        appUser.setSex(2);
        appUser.setNationality("");
        appUserMapper.updateAppUser(appUser);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getUserInfo(String openId) {
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);
        List<AppUser> appUsers = iAppUserService.selectAppUserList(appUser);
        if(appUsers.size()<=0){
            throw new CustomException("获取用户信息失败，用户不存在", HttpStatus.ERROR);
        }
        AppUser appUser1 = appUsers.get(0);
        String phone1 = appUser1.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
        //String identitynumber1 = appUser1.getIdentitynumber().replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1****$2");
        appUser1.setPhone(phone1);
        //appUser1.setIdentitynumber(identitynumber1);
        return AjaxResult.success(appUser1);

    }
}
